#!/bin/bash

param=$1

function _is_running() {
    process=$1

    out=$(ps wwx -U $(whoami) | pcregrep "^\s*$( cat $HOME/pid/${process}.pid )" | \
        grep $process)

    if [[ $out ]]
    then
        echo $out
        return 1
    else
        return 0
    fi
}

function _store_pid() {
    process=$1
    # pid=$(ps x -U $(whoami) | grep $process | perl -ne 'm/^\s*(\d+)\s+/; print $1')
    pid=$(ps x -U $(whoami) | pgrep $process)

    if [[ $pid ]]
    then
        if [[ ! -d $HOME/pid/ ]]
        then
            mkdir -p $HOME/pid/
        fi
        echo -n $pid > $HOME/pid/${process}.pid

        return $pid
    else
        return 0
    fi
}

function _get_pid() {
    process=$1

    if [[ -e $HOME/pid/${process}.pid ]]
    then
        cat $HOME/pid/${process}.pid
    fi
}

case $param in
start)
    if [[ ! $( _is_running bearerbox ) ]] && [[ ! $( _is_running smsbox ) ]]
    then
        for p in bearerbox smsbox
        do
            echo -n "Starting $p ..."
            (nohup $HOME/sbin/$p $HOME/conf/kannel.conf) 2>&1 >/dev/null &
            sleep 1

            _store_pid $p
            if [[ $? > 0 ]]
            then
                echo "success"
            else
                echo "failed!"
            fi
        done
    else 
        echo "Oops! found a running instance:"
        _is_running bearerbox
        _is_running smsbox
        exit 1
    fi
    ;;
stop)
    for p in bearerbox smsbox
    do
        if [[ $( _is_running $p ) ]]
        then
            echo -n "Killing $p ... "
            kill -9 $(_get_pid $p)
            echo 'done'
        else 
            echo "$p not running"
        fi
    done
    ;;
*)
    echo "Usage: $0 start|stop"
    ;;
esac
